package com.itheima.template;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.itheima.configproperties.Imgproperties;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @Author：wsm
 * @Date：2021/12/21/18:10
 * @Description：
 */
public class PushImgTemplate {

    private OSS ossClient;

    private Imgproperties imgproperties;

    public PushImgTemplate(Imgproperties imgproperties) {
        this.imgproperties = imgproperties;
    }
    public  String putimg(String fileName, InputStream inputStream){
        String path = DateUtil.format(new Date(), "yyyy/MM/dd")
                + UUID.randomUUID().toString()
                + fileName.substring(fileName.lastIndexOf("."));

        String objectName = path;

        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(imgproperties.getEndpoint(), imgproperties.getAccessKeyId(), imgproperties.getAccessKeySecret());

//            String content = "Hello OSS";
//            new ByteArrayInputStream(content.getBytes())
            ossClient.putObject(imgproperties.getBucketName(), objectName, inputStream);
        } catch(OSSException e){
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        //https://tanhua-img1234.oss-cn-beijing.aliyuncs.com
        return "https://tanhua-img12345.oss-cn-beijing.aliyuncs.com/"+path;
    }
}
